<template>
  <div class="search">
    <input class="search-input"
           type="text"
           placeholder="请输入城市名或拼音"
           v-model="keyword"
    >
    <div class="search-contnet"
         ref="content"
         v-show="showList()"
    >
      <ul>
        <li class="item border-bottom"
            v-for="item of list"
            :key="item.id"
            @click="handleCityClick(item.name)"
        >
          {{item.name}}
        </li>
        <li class="item border-bottom"
            v-show="hasList()"
        >
          没有找到匹配结果
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import BScroll from 'better-scroll'
import { mapActions } from 'vuex'
export default {
  name: 'CitySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      keyword: '',
      list: [],
      timer: null
    }
  },
  mounted () {
    this.scroll = new BScroll(this.$refs.content)
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyword) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let item in this.cities) {
          this.cities[item].forEach((value) => {
            if (value.name.indexOf(this.keyword) > -1 ||
                value.spell.indexOf(this.keyword) > -1) {
              result.push(value)
            }
          })
        }
        this.list = result
      }, 100)
    }
  },
  methods: {
    showList () {
      return this.keyword
    },
    hasList () {
      return !this.list.length
    },
    handleCityClick (city) {
      this.changeCity(city)
      this.$router.push('/')
    },
    ...mapActions(['changeCity'])
  }
}
</script>

<style lang="stylus" scoped>
  @import '~styles/varibles.styl'
  .search
    height: .72rem
    padding: 0 .1rem
    background: $bgColor
    .search-input
      box-sizing: border-box
      width: 100%
      line-height: .62rem
      padding: 0 .1rem
      text-align: center
      border-radius: .06rem
      color: #666
    .search-contnet
      position: absolute
      overflow: hidden
      top: 1.58rem
      left: 0
      right: 0
      bottom: 0
      background: #fff
      z-index: 2
      .item
        padding-left: .1rem
        line-height: .7rem
</style>
